/**
 * $version:  0.1 
 * $Date: 2012-05-25
 *
 * Copyright (C) 2010-2012 Jawa Software. All rights reserved.
 *
 */
package org.jawa.admin;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * 上传文件
 * @author Y-N
 */
public class UploadServlet extends HttpServlet {
	private static final Logger Log = LoggerFactory.getLogger(UploadServlet.class);

	//上传最大文件
	private static int MAX_FILE_SIZE = 50 * 1024 * 1024;
	//最大内存占用
	private static int MAX_MEM_SIZE = 4 * 1024;

	//上传文件文件夹
	private String UPLOAD_FILE_DIR;
	private String REPOSITORY_DIR;
	private boolean isMultipart;

	private File file;

	public void init() {
		String MAX_FILE_SIZE_STR = getServletContext().getInitParameter("MAX_FILE_SIZE");
		String MAX_MEM_SIZE_STR = getServletContext().getInitParameter("MAX_MEM_SIZE");

		UPLOAD_FILE_DIR = getServletContext().getInitParameter("upload_file_dir");
		REPOSITORY_DIR = getServletContext().getInitParameter("repository_dir");
		MAX_FILE_SIZE = NumberUtils.toInt(MAX_FILE_SIZE_STR, MAX_FILE_SIZE);
		MAX_MEM_SIZE = NumberUtils.toInt(MAX_MEM_SIZE_STR, MAX_MEM_SIZE);

		if (UPLOAD_FILE_DIR == null) {
			UPLOAD_FILE_DIR = "resources";
		}

		Log.debug("上传文件目录: " + UPLOAD_FILE_DIR);
		Log.debug("文件最大大小: " + MAX_FILE_SIZE);
		Log.debug("最大内存占用: " + MAX_MEM_SIZE);
	}

	/**
	 * 上传文件,一次只接受一个文件上传.
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			java.io.IOException {

		String reName = "false";
		String uploadDir = "";

		isMultipart = ServletFileUpload.isMultipartContent(request);
		java.io.PrintWriter out = response.getWriter();
		if (!isMultipart) {
			out.println("-1");
			return;
		}
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(MAX_MEM_SIZE);

		//临时目录
		if (StringUtils.isEmpty(REPOSITORY_DIR)) {
			factory.setRepository(SystemUtils.getJavaIoTmpDir());
		} else {
			factory.setRepository(new File(REPOSITORY_DIR));
		}

		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(MAX_FILE_SIZE);

		try {
			List fileItems = upload.parseRequest(request);

			Iterator i = fileItems.iterator();
			FileItem uploadFile = null;
			while (i.hasNext()) {
				FileItem fi = (FileItem) i.next();
				String fieldName = fi.getFieldName();
				if (!fi.isFormField()) {
					//文件上传成功,一次只传一个文件
					uploadFile = fi;
					break;
				} else {
					if (StringUtils.equalsIgnoreCase("reName", fieldName)) {
						reName = fi.getString();
					}
					if (StringUtils.equalsIgnoreCase("uploadDir", fieldName)) {
						uploadDir = fi.getString();
					}
				}
			}

			if (null != uploadFile) {
				String fileName = uploadFile.getName();
				String contentType = uploadFile.getContentType();
				boolean isInMemory = uploadFile.isInMemory();
				long sizeInBytes = uploadFile.getSize();

				String savePath = UPLOAD_FILE_DIR;

				if (StringUtils.isNotEmpty(uploadDir)) {
					savePath = savePath + File.separator + uploadDir;
				}
				
				//创建文件夹
				if(!new File(savePath).exists()){
					new File(savePath).mkdirs();
				}
				
				if ("true".equalsIgnoreCase(reName)) {
					String extension = FilenameUtils.getExtension(fileName);
					savePath = savePath + File.separator + System.currentTimeMillis() +"."+ extension;
				} else {
					if (fileName.lastIndexOf("\\") >= 0) {
						savePath = savePath + File.separator + fileName.substring(fileName.lastIndexOf("\\"));
					} else {
						savePath = savePath + File.separator + fileName.substring(fileName.lastIndexOf("\\") + 1);
					}
				}
				//写入文件

				file =  new File(request.getSession().getServletContext().getRealPath(savePath));
				uploadFile.write(file);
				
				Log.debug("上传文件名称:"+ fileName);
				Log.debug("上传文件类型:"+ contentType);
				Log.debug("上传占用内存:"+ isInMemory);
				Log.debug("上传占用大小:"+ sizeInBytes);
				Log.debug("上传目的地:"+ savePath);
				
				savePath = FilenameUtils.separatorsToUnix(savePath);
				
				//返回上传文件的生成位置
				out.println(savePath);
			}


		} catch (Exception ex) {
			Log.error("上传文件出错", ex);
		}
	}
}
